<template>
    <el-upload
        class="avatar-uploader"
        :action="action"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload"
    >
        <img v-if="imageUrl" :src="imageUrl" class="avatar" />
        <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
    </el-upload>
</template>

<script setup lang="ts">
import { ref, defineProps, defineEmits, ToRef } from 'vue';
import { ElMessage } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';
import type { UploadProps } from 'element-plus';
let props = defineProps(['uploadConfig', 'prop']);
let emit = defineEmits(['getUrl']);
let { action } = props.uploadConfig;
const imageUrl: ToRef<string> = ref('');
const handleAvatarSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
    imageUrl.value = props.uploadConfig.action + '/' + response.url;
    let urlInfo: any = {
        url: imageUrl.value,
        prop: props.prop
    };
    emit('getUrl', urlInfo);
};

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    console.log(props.uploadConfig.type);
    let typeTrue: boolean = false;
    let sizeTrue: boolean = false;
    props.uploadConfig.type.forEach((item: string) => {
        if (rawFile.type === 'image/' + item) {
            typeTrue = true;
        }
        if (rawFile.size / 1024 / 1024 < props.uploadConfig.size) {
            sizeTrue = true;
        }
    });
    if (!typeTrue) {
        ElMessage.error(`图片格式只能是${[...props.uploadConfig.type]}格式`);
        return false;
    }
    if (!sizeTrue) {
        ElMessage.error(`图片格式大小不可大于${props.uploadConfig.size}M!`);
        return false;
    }
    return true;
};
</script>

<style scoped>
::v-deep.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}
::v-deep.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

::v-deep.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

::v-deep.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>
